//
//  LoginViewController.m
//  Router
//
//  Created by teki on 15/10/13.
//  Copyright © 2015年 dc. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "BindWIFIListViewController.h"
#import "BaseNavigationViewController.h"
#import "CustomTextField.h"
#import "AppDelegate.h"
#import "UserHelper.h"
#import "LoginPromtView.h"
#import "LoginResponseModel.h"
#import "UserModel.h"
#import "DiscoverHelper.h"
#import "DynamicIPViewController.h"
#import "FixedIPViewController.h"
#import "BroadbandIPViewController.h"
#import "ForgetPasswordViewController.h"
#import "DiscoverNewWIFIView.h"


@interface LoginViewController ()<UITextFieldDelegate, UIScrollViewDelegate>
@property (nonatomic, strong) UIScrollView *rootScrollView;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) CustomTextField *phoneTextField;
@property (nonatomic, strong) CustomTextField *passwordTextField;

@property (nonatomic, strong) UIButton *loginButton;
@property (nonatomic, strong) DiscoverNewWIFIView *discoverNewWIFIView;
@property (nonatomic, strong) UserHelper *userHelper;
@property (nonatomic, strong) DiscoverHelper *discoverHelper;

@property (nonatomic, assign) NetType netType;
/// 当前wifi是否被绑定
@property (nonatomic, assign) BOOL isCurrentWIFIbeBinded;
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#5fa756"];
    
    _discoverHelper = [[DiscoverHelper alloc] init];

    self.userHelper = [[UserHelper alloc] init];
    //启用键盘监听
    [self enableKeyboardNotification];
    [self initContentView];
    
    
    LoginResponseModel *model = [UserSingleton shareInstance].userModel;
    UserModel *user = model.user[0];
    self.phoneTextField.textField.text = user.userName;
    self.passwordTextField.textField.text = [UserSingleton shareInstance].password;
    
    
//    [self performSelector:@selector(hiddenNewWIFIView) withObject:nil afterDelay:2.0];
    // Do any additional setup after loading the view.
}




- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
//    [self showNewWIFIView];
    
    [self findNewWIFI];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(findNewWIFI) name:UIApplicationDidBecomeActiveNotification object:nil];
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
}



- (void)showNewWIFIView
{
    [self.view addSubview:self.discoverNewWIFIView];
    self.discoverNewWIFIView.hidden = NO;
    WEAKSELF
    [self.discoverNewWIFIView setSettingButtonBlock:^{
        STRONGSELF
        [strongSelf settingButtonClick];
    }];
    [self.discoverNewWIFIView makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(20);
        make.left.right.equalTo(self.view);
        make.height.equalTo(44);
    }];
    
    
//    [self.rootScrollView remakeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.discoverNewWIFIView.bottom);
//        make.left.right.equalTo(self.view);
//        make.bottom.equalTo(self.view);
//    }];
}



- (void)hiddenNewWIFIView
{
    [self.discoverNewWIFIView hidden];
}

#pragma mark 键盘事件
-(void)keyboardWillShowKeyHeight:(CGFloat)keyHeight
{
    [super setKeyboardShowView:self.passwordTextField keyboardHeight:keyHeight];
}

-(void)keyboardWillHide
{
    self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark 初始化UI
- (void)initContentView
{
    //内容跟视图
    _rootScrollView=[[UIScrollView alloc]init];
    _rootScrollView.showsVerticalScrollIndicator = NO;
    _rootScrollView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:_rootScrollView];
    [_rootScrollView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    
    UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGestureClick:)];
    [_rootScrollView addGestureRecognizer:tapGesture];
    //内容视图
    _contentView = UIView.new;
    [_rootScrollView addSubview:_contentView];
    _contentView.backgroundColor = [UIColor clearColor];
    [_contentView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_rootScrollView);
        make.width.equalTo(_rootScrollView);
    }];

    
    /// logo
    UIImageView *logoImageView = [UIImageView new];
    logoImageView.translatesAutoresizingMaskIntoConstraints = NO;
    UIImage *logoImage = [UIImage imageNamed:@"land_logo"];
    logoImageView.image = logoImage;
    [_contentView addSubview:logoImageView];
    [logoImageView makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(80);
        make.size.equalTo(logoImage.size);
    }];
    
    int fontSize = 14;
    CGFloat padding = 23.0f;
    CGFloat height = 45;
    _phoneTextField = [[CustomTextField alloc]initWithType:CustomTextFieldTypePhone target:self FontSize:fontSize];
    _phoneTextField.textField.keyboardType = UIKeyboardTypeEmailAddress;
    _phoneTextField.attributePlaceholder = [[NSAttributedString alloc] initWithString:@"请输入您的用户名" attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    _phoneTextField.textField.textColor = [UIColor whiteColor];
    _phoneTextField.textField.returnKeyType = UIReturnKeyNext;
    [_contentView addSubview:_phoneTextField];
    
    [_phoneTextField makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(logoImageView.bottom).offset(40);
        make.left.equalTo(padding);
        make.right.equalTo(-padding);
        make.centerX.equalTo(_contentView);
        make.height.equalTo(height);
    }];
    
    _passwordTextField = [[CustomTextField alloc]initWithType:CustomTextFieldTypePwd target:self FontSize:fontSize];
    _passwordTextField.attributePlaceholder = [[NSAttributedString alloc] initWithString:@"请输入您的密码" attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    _passwordTextField.textField.textColor = [UIColor whiteColor];
    _passwordTextField.textField.returnKeyType = UIReturnKeyDone;
    [_contentView addSubview:_passwordTextField];
    [_passwordTextField makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_phoneTextField.bottom).offset(padding);
        make.left.equalTo(padding);
        make.right.equalTo(-padding);
        make.centerX.equalTo(_contentView);
        make.height.equalTo(height);
    }];
    
    
    self.loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _loginButton.translatesAutoresizingMaskIntoConstraints = NO;
    _loginButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    [_loginButton setTitle:@"登  录" forState:UIControlStateNormal];
    _loginButton.layer.cornerRadius = 5.0f;
    _loginButton.layer.masksToBounds = YES;
    [_loginButton setTitleColor:NavgationBarBackgroundColor forState:UIControlStateNormal];
    [_loginButton setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    [_loginButton setBackgroundImage:[UIImage imageWithColor:RGB(202, 202, 202)] forState:UIControlStateSelected];
    [_loginButton addTarget:self action:@selector(loginButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [_contentView addSubview:_loginButton];
    [_loginButton makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_passwordTextField.bottom).offset(26);
        make.left.equalTo(padding);
        make.right.equalTo(-padding);
        make.height.equalTo(height);
    }];
    
    
    UIButton *registerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    registerButton.translatesAutoresizingMaskIntoConstraints = NO;
    registerButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    [registerButton setTitle:@"马上注册" forState:UIControlStateNormal];
    registerButton.layer.borderColor = [UIColor whiteColor].CGColor;
    registerButton.layer.borderWidth =1.0f;
    registerButton.layer.cornerRadius = 5.0f;
    registerButton.layer.masksToBounds = YES;
    [registerButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [registerButton setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHexString:@"#77c66d"]] forState:UIControlStateNormal];
    [registerButton setBackgroundImage:[UIImage imageWithColor:RGB(78 , 152, 69)] forState:UIControlStateSelected];
    [registerButton addTarget:self action:@selector(registerButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [_contentView addSubview:registerButton];
    
    
    UIButton *forgetPasswordButton = [UIButton buttonWithType:UIButtonTypeCustom];
    forgetPasswordButton.translatesAutoresizingMaskIntoConstraints = NO;
    forgetPasswordButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    [forgetPasswordButton setTitle:@"忘记密码" forState:UIControlStateNormal];
    forgetPasswordButton.layer.borderColor = [UIColor whiteColor].CGColor;
    forgetPasswordButton.layer.borderWidth =1.0f;
    forgetPasswordButton.layer.cornerRadius = 5.0f;
    forgetPasswordButton.layer.masksToBounds = YES;
    [forgetPasswordButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [forgetPasswordButton setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHexString:@"#77c66d"]] forState:UIControlStateNormal];
    [forgetPasswordButton setBackgroundImage:[UIImage imageWithColor:RGB(78 , 152, 69)] forState:UIControlStateSelected];
    [forgetPasswordButton addTarget:self action:@selector(forgetPasswordButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [_contentView addSubview:forgetPasswordButton];
    
    [registerButton makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_loginButton.bottom).offset(50);
        make.left.equalTo(padding);
        make.right.equalTo(forgetPasswordButton.left).offset(-10);
        make.height.equalTo(height);
        make.width.equalTo(forgetPasswordButton);
        make.bottom.equalTo(_contentView.bottom).offset(-30);
    }];
    
    [forgetPasswordButton makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(registerButton.right).offset(10);
        make.top.equalTo(registerButton);
        make.right.equalTo(-padding);
        make.height.equalTo(height);
    }];

    
}


#pragma mark -
#pragma mark   IBActions
- (void)tapGestureClick:(UITapGestureRecognizer *)guesture
{
    [self resignAllTextFiled];
}


- (void)resignAllTextFiled
{
    [_phoneTextField.textField resignFirstResponder];
    [_passwordTextField.textField resignFirstResponder];
}



- (void)loginButtonPressed:(UIButton *)sender
{
    [self resignAllTextFiled];
    [self loginRequest];
//    [self pushViewControllerWithClassName:@"BroadbandIPViewController"];
}

- (void)registerButtonPressed:(UIButton *)sender
{

    RegisterViewController *registerVC = [[RegisterViewController alloc]init];
    [self.navigationController pushViewController:registerVC animated:YES];

}

- (void)forgetPasswordButtonPressed:(UIButton *)sender
{
    ForgetPasswordViewController *forgetVC = [[ForgetPasswordViewController alloc]init];
    forgetVC.controllerType = ViewControllerTypeFindBackPassword;
    [self.navigationController pushViewController:forgetVC animated:YES];
    
}



- (void)settingButtonClick
{
    [self gotoWithType:self.netType];
}

#pragma mark UITextField Delegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.phoneTextField.textField) {
        [self.passwordTextField.textField becomeFirstResponder];
    }else if (textField == self.passwordTextField.textField){
        [textField resignFirstResponder];
    }
    
    return YES;
}


- (void)gotoWithType:(NetType)type
{
    NSString *className;
    if (type == NetTypeDHCP)
    {
        className = NSStringFromClass([DynamicIPViewController class]);
    }
    else if (type == NetTypeIP)
    {
        className = NSStringFromClass([FixedIPViewController class]);
    }
    else if (type == NetTypePPPOE)
    {
        className = NSStringFromClass([BroadbandIPViewController class]);
    }
    [self pushViewControllerWithClassName:className];
}

#pragma mark -
#pragma mark   Requests
- (void)findNewWIFI
{
    __weak __typeof(self)weakSelf = self;
    
    [_discoverHelper discoverWIFISuccess:^(BOOL succ, id responseObject, NSString *msg) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSLog(@"responseObject:%@",responseObject);
        if (responseObject)
        {
            NSString *info = responseObject[@"info"];
            if ([info isEqualToString:@"InterNetNotConnected"])
            {
                NSString *type = responseObject[@"type"];
                if ([type isEqualToString:@"dhcp"])
                {
                    strongSelf.netType = NetTypeDHCP;
                }
                else if ([type isEqualToString:@"static"]){
                    strongSelf.netType = NetTypePPPOE;
                }
                else if ([type isEqualToString:@"ip"]){
                    strongSelf.netType = NetTypeIP;
                }
                else if ([type isEqualToString:@"linkoff"])
                {
                    [strongSelf promptMessage:@"网线没有插入WAN口!"];
                }
            }
            else if ([info isEqualToString:@"InterNetConnected"])
            {
                NSString *deviceID = responseObject[@"deviceID"];
                [strongSelf checkDeviceInBindWithDeviceID:deviceID];
            }
        }
       } failure:^(NSError *error) {
        /// 可以判断这个用的不是小叶WIFI
//        NSString *failedReason = [error localizedDescription];
           [weakSelf promptMessage:@"您当前连的不是小叶WIFI"];
           weakSelf.isCurrentWIFIbeBinded = YES; /// 如果不是小叶WIFI 进入主界面
           [self hiddenNewWIFIView];
       }];
}



- (void)checkDeviceInBindWithDeviceID:(NSString *)deviceID
{
    if (deviceID) {
        [self.discoverHelper getWIFIBindDeviceWithDeviceID:deviceID success:^(BOOL succ, id responseObject, NSString *msg) {
            if (responseObject) {
                BOOL bindOrNot = [responseObject[@"isBind"] boolValue];
                if (!bindOrNot)
                {
                    [self showNewWIFIView];
                    self.discoverNewWIFIView.showText = @"发现未绑定的小叶WIFI,登录后绑定";
                    self.discoverNewWIFIView.isShowSettingButton = NO;
                }
                else
                {
                    self.isCurrentWIFIbeBinded = YES;
                    [self hiddenNewWIFIView];
                }
            }
        } failure:^(NSError *error) {
            NSString *failedReason = [error localizedDescription];
            [self stopActivityWithActivity:self.activity title:failedReason];
        }];
    }
    
}



- (void)loginRequest
{

    NSString *phone = _phoneTextField.textField.text;
    NSString *password = _passwordTextField.textField.text;
//    if (![phone isValidate]) {
//        [self promptMessage:@"用户名格式不正确!"];
//        return;
//    }
    
    if ([password checkEmpty]) {
        [self promptMessage:@"密码不能为空!"];
        return;
    }
    
    self.activity = [self startActivityWithTitle:@"正在登录,请稍候..."];
    WEAKSELF
    [self.userHelper loginWithPhone:phone password:password success:^(BOOL succ, id responseObject, NSString *msg) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        if (succ) {
            [strongSelf stopActivityWithActivity:strongSelf.activity title:nil];
            LoginResponseModel *model = (LoginResponseModel *)responseObject;
            UserSingleton *singleton = [UserSingleton shareInstance];
            
            singleton.userModel = model;
            NSArray *array = [model.stations sortedArrayUsingComparator:^NSComparisonResult(StationModel *  _Nonnull obj1, StationModel*  _Nonnull obj2) {
                NSNumber *number1 = @(obj1.master);
                NSNumber *number2 = @(obj2.master);
                return [number2 compare:number1];
            }];
            singleton.userModel.stations = array;
            singleton.password = password;
            [singleton saveData];
            
            /// 当前设备被绑定。并且有绑定小叶设备
            if (strongSelf.isCurrentWIFIbeBinded && [model.bindDevice count]>0)
            {
                UIStoryboard *main = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                UIViewController *mainVC = [main instantiateViewControllerWithIdentifier:@"MainVC"];
                ApplicationDelegate.window.rootViewController = mainVC;
            }
            else{
                BindWIFIListViewController *buynowVC = [[BindWIFIListViewController alloc] init];
                BaseNavigationViewController *baseNav = [[BaseNavigationViewController alloc] initWithRootViewController:buynowVC];
                ApplicationDelegate.window.rootViewController = baseNav;
            }
        }
        else{
            [strongSelf stopActivityWithActivity:strongSelf.activity title:nil];
            LoginPromtView *view = [LoginPromtView loadViewFromNib];
            [view show];
        }
    } failure:^(NSError *error) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSString *failedReason = [error localizedDescription];
        [strongSelf stopActivityWithActivity:strongSelf.activity title:failedReason];
    }];
}



#pragma mark -
#pragma mark   setters and getters
- (DiscoverNewWIFIView *)discoverNewWIFIView
{
    if (_discoverNewWIFIView == nil) {
        _discoverNewWIFIView = [DiscoverNewWIFIView loadViewFromNib];
    }
    return _discoverNewWIFIView;
}
@end
